package gerador;

import java.sql.SQLException;
import java.util.StringTokenizer;

import conexao.Conexao;

import uteis.Constantes;
import xml.LeXML;

public class Relacionamento {
	
	public static void main(String[] args) {
		LeXML.ler();
		Conexao con = new Conexao();
		String select ="";
		Conexao con2 = new Conexao();
    try {
        con.conectar(Constantes.base,Constantes.local,
                Constantes.user,Constantes.senha);
        select = "SELECT pg_class.relname AS tabela, pg_get_constraintdef(pg_constraint.oid) AS definicao_da_restricao "+
        		  "FROM pg_namespace JOIN pg_class ON pg_namespace.oid=pg_class.relnamespace "+
        		  "JOIN pg_constraint ON pg_class.oid=pg_constraint.conrelid "+
        		  "WHERE pg_namespace.nspname='public' "+
        		  "AND pg_class.relkind='r' and pg_constraint.contype='f' "+
        		  "ORDER BY pg_class.relname;";
       
        

        System.out.println(select);
        Conexao.pst = Conexao.conn.prepareStatement(select);
		Conexao.rs = Conexao.pst.executeQuery();

		while (Conexao.rs.next()) {
			System.out.println(Conexao.rs.getString(1));
			System.out.println(Conexao.rs.getString(2));
			String s = Conexao.rs.getString(2);
			String s1[] = s.split(" REFERENCES ");
			String s2 = s1[s1.length-1];
			s = s1[0].replace("FOREIGN KEY (", "").replace(")", "");
			
			StringTokenizer filtro = new StringTokenizer(s2,"()");
			String coluna = s;
			String tabelaReferencia = filtro.nextElement().toString();
			String id = filtro.nextElement().toString();
			
			System.out.println(s);
			System.out.println(tabelaReferencia);
			System.out.println(id);
			
			
			con2.conectar(Constantes.base,Constantes.local,
	                Constantes.user,Constantes.senha);
	        select = "select  TABLE_NAME, COLUMN_NAME, DATA_TYPE , IS_NULLABLE from information_schema.columns where  TABLE_CATALOG ='"
                    + Constantes.base + "' and table_schema='public' and TABLE_NAME = '"+tabelaReferencia+"'";
	        System.out.println(select);
	        Conexao.pst = Conexao.conn.prepareStatement(select);
			Conexao.rs = Conexao.pst.executeQuery();

			while (Conexao.rs.next()) {
				System.out.println(Conexao.rs.getString(2));
			}
			
			
			
		}
    } catch (SQLException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

	}
}
